package com.lucien.admin.controller.chat;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.lucien.common.result.GlobalResult;
import com.lucien.common.utils.JsonUtil;
import com.lucien.framework.rabbitmq.constants.RabbitCons;
import com.lucien.system.domain.ChatMessage;
import com.lucien.system.domain.SysGroupMessage;
import com.lucien.system.domain.SysUser;
import com.lucien.system.service.ChatMessageService;
import com.lucien.system.service.SysGroupMessageService;
import com.lucien.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Date;

/**
 * @Author: Lucien
 * @Description:
 * @Date: Created in 2021/5/3
 */
@RestController
@Api(tags = "消息接口")
public class ChatController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SysUserService userService;

    @Autowired
    private ChatMessageService messageService;

    @Autowired
    private SysGroupMessageService groupMessageService;


    /**
     * 系统推送给单人
     *
     * @param username
     * @param content
     */
    @ResponseBody
    @GetMapping("/systemSend")
    @ApiOperation(value = "系统推送给单人")
    public GlobalResult sendToOne(@RequestParam("username") String username, @RequestParam("content") String content) {
        ChatMessage chatMessage = new ChatMessage();
        SysUser sysUser = userService.selectByUsername(username);
        chatMessage.setFromId(25);
        chatMessage.setFromName("系统消息");
        chatMessage.setFromProfile(userService.selectByUserId(25).getUserProfile());
        chatMessage.setToId(sysUser.getId());
        chatMessage.setToName(username);
        chatMessage.setMessageTypeId(2);
        chatMessage.setContent(content);
        chatMessage.setCreateTime(new Date());

        int result = messageService.insertMsg(chatMessage);
        if (result == 1){
            rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(chatMessage));
            return GlobalResult.success("消息发送成功", result);
        }else {
            return GlobalResult.error("消息记录失败" ,result);
        }
    }

    @ResponseBody
    @GetMapping("/sendtoone")
    @ApiOperation(value = "推送给单人")
    public GlobalResult sendToOne(@RequestParam("formName") String formName,
                          @RequestParam("toName") String toName,
                          @RequestParam("content") String content){
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setFromId(userService.selectByUsername(formName).getId());
        chatMessage.setFromName(formName);
        chatMessage.setFromProfile(userService.selectByUsername(formName).getUserProfile());
        chatMessage.setToId(userService.selectByUsername(toName).getId());
        chatMessage.setToName(toName);
        chatMessage.setMessageTypeId(2);
        chatMessage.setContent(content);
        chatMessage.setCreateTime(new Date());

        int result = messageService.insertMsg(chatMessage);
        if (result == 1){
            rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(chatMessage));
            return GlobalResult.success("消息发送成功", result);
        }else {
            return GlobalResult.error("消息记录失败" ,result);
        }
    }

    /**
     * @MessageMapping 指定目的地是,用于客户端访问,并且返回值会发到消息代理
     * @SendTo 注解重写了消息代理的目的地,用于指定消息发送到哪里(simpmessagingtemplate)也可以实现同样的效果。
     */

    /**
     * 接收 客户端传过来的消息 通过setSender和type 来判别时单发还是群发
     * @param chatMessage   客户端推送的消息内容
     * @param principal     客户端携带的识别信息
     */
    @MessageMapping("/sendMessageTest")
    public void sendMessageTest(@Payload ChatMessage chatMessage, Principal principal) {
        try {
            messageService.insertMsg(chatMessage);
            System.out.println("stompClient.send插入聊天记录");
            //将消息发送到rabbitmq的主题交换机上，携带路由键
            //推送完触发回调函数
            //消息被 消费者监听器 消费了
            rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(chatMessage));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @MessageMapping("/sendMsgGroup")
    public void sendMsgGroup(@Payload SysGroupMessage groupMessage, Principal principal){
        try {
            groupMessageService.insert(groupMessage);
            System.out.println("群聊信息插入");
            rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(groupMessage));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 接收 客户端传过来的消息 上线消息
     */
    @MessageMapping("/addUser")
    public void addUser(@Payload ChatMessage chatMessage){
        System.out.println("有用户加入到了websocket 消息室" + chatMessage.getFromName());
        try {
            System.out.println("chatMessage:"+chatMessage.toString());
            rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(chatMessage));
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    @GetMapping("sendtotest")
    @SendTo("chatroom/sendtotest")
    @ApiOperation(value = "sendTo测试")
    public GlobalResult sendTo(String username, String content){
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setFromId(userService.selectByUserId(25).getId());
        chatMessage.setFromName(userService.selectByUserId(25).getUsername());
        chatMessage.setFromProfile(userService.selectByUserId(25).getUserProfile());
        chatMessage.setToId(userService.selectByUsername(username).getId());
        chatMessage.setToName(username);
        chatMessage.setMessageTypeId(2);
        chatMessage.setContent(content);
        chatMessage.setCreateTime(new Date());

        int result = messageService.insertMsg(chatMessage);
        if (result == 1){
            rabbitTemplate.convertAndSend(RabbitCons.TOPIC_EXCHANGE, RabbitCons.TOPIC_ROUTING_KEY, JSONObject.toJSONString(chatMessage));
            return GlobalResult.success("消息发送成功", result);
        }else {
            return GlobalResult.error("消息记录失败" ,result);
        }
    }
}
